import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:get/route_manager.dart';
import 'package:gt_flutter_admin/models/index.dart';
import 'package:gt_flutter_admin/res/strings.dart';
import 'package:gt_flutter_admin/utils/storage_utils.dart';

import 'toast_utils.dart';

class RequestUtils {
  RequestUtils._internal();

  /// 网络请求配置
  static final Dio dio = Dio(
    BaseOptions(
      baseUrl: SERVER_HOST,
      connectTimeout: const Duration(milliseconds: 5000),
      receiveTimeout: const Duration(milliseconds: 3000),
    ),
  );

  /// 初始化dio
  static void init() {
    //添加拦截器
    dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (RequestOptions options, handler) {
          print("请求之前");

          String? token = StorageUtils.readToken();
          options.headers['Authorization'] = 'Bearer ${token ?? ""}';

          return handler.next(options);
        },
        onResponse: (Response response, handler) {
          print("响应之前");

          return handler.next(response);
        },
        onError: (DioException e, handler) {
          print("错误之前");
          handleError(e);
          return handler.next(e);
        },
      ),
    );
  }

  /// error统一处理
  static void handleError(DioException e) {
    switch (e.type) {
      case DioExceptionType.connectionTimeout:
        print("连接超时");
        break;
      case DioExceptionType.sendTimeout:
        print("请求超时");
        break;
      case DioExceptionType.receiveTimeout:
        print("响应超时");
        break;
      case DioExceptionType.badResponse:
        print("请求错误");

        if (e.response!.statusCode == 401) {
          ToastUtils.error('请先登录');
          Navigator.of(Get.context!).pop();
        } else {
          Result result = Result.fromJson(e.response!.data);
          ToastUtils.error(result.message);
        }

        break;
      case DioExceptionType.cancel:
        print("请求取消");
        break;
      default:
        print("未知错误");
        break;
    }
  }

  /// get请求
  static Future<Result> get(String url, [Map<String, dynamic>? params]) {
    Future<Response<dynamic>> response;
    if (params != null) {
      response = dio.get(url, queryParameters: params);
    } else {
      response = dio.get(url);
    }

    return response.then((response) => Result.fromJson(response.data));
  }

  /// post请求
  static Future<Result> post(String url, [Map<String, dynamic>? data]) {
    return dio
        .post(url, data: data)
        .then((response) => Result.fromJson(response.data));
  }

  /// post请求
  static Future<List> postFormData(String url, FormData data) {
    return dio.post(url, data: data).then((response) {
      return response.data['data'];
    });
  }

  /// delete请求
  static Future<Result> delete(String url, num id) {
    return dio
        .delete('$url/$id')
        .then((response) => Result.fromJson(response.data));
  }

  /// put请求
  static Future<Result> put(String url, [Map<String, dynamic>? data]) {
    return dio
        .put(url, data: data)
        .then((response) => Result.fromJson(response.data));
  }

  /// 下载文件
  static Future<Result> downloadFile(urlPath, savePath) {
    Future<Response<dynamic>>? res;
    try {
      res = dio.download(
        urlPath,
        savePath,
        onReceiveProgress: (int count, int total) {
          // 进度
          print("$count $total");
        },
      );
    } on DioException catch (e) {
      handleError(e);
    }
    return res!.then((r) => Result.fromJson(r.data));
  }
}
